package com.artisan.si.controller;

import com.artisan.si.model.User;
import com.artisan.si.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 * 接收 HTTP 请求并将用户注册请求发送到 Spring Integration 流程中处理
 */
@RestController
@RequestMapping("/users")
@CrossOrigin(origins = "*") // 允许跨域请求（开发环境）
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    
    private final MessageChannel userInputChannel;
    private final UserService userService;

    /**
     * 构造函数注入消息通道和用户服务
     * @param userInputChannel Spring Integration 的用户输入通道
     * @param userService 用户服务
     */
    public UserController(MessageChannel userInputChannel, UserService userService) {
        this.userInputChannel = userInputChannel;
        this.userService = userService;
    }

    /**
     * 用户注册的 REST 端点（通过 Spring Integration 流程）
     * @param user 用户信息（从请求体中获取）
     * @return 响应信息
     */
    @PostMapping
    public Map<String, Object> registerUser(@RequestBody User user) {
        logger.info("接收到用户注册请求: {}", user);
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 基本验证
            if (user.getEmail() == null || user.getEmail().trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "邮箱不能为空");
                return response;
            }
            
            if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "用户名不能为空");
                return response;
            }
            
            // 将用户封装为消息并发送到集成流程
            boolean sent = userInputChannel.send(new GenericMessage<>(user));
            
            if (sent) {
                response.put("success", true);
                response.put("message", "用户注册请求已成功提交处理: " + user.getEmail());
                response.put("user", user);
                logger.info("用户注册请求已发送到集成流程: {}", user.getEmail());
            } else {
                response.put("success", false);
                response.put("message", "用户注册提交失败，请稍后重试");
                logger.error("用户注册请求发送到集成流程失败: {}", user);
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "处理用户注册时发生错误: " + e.getMessage());
            logger.error("处理用户注册请求时发生异常", e);
        }
        
        return response;
    }

    /**
     * 直接注册用户（绕过 Spring Integration，用于测试）
     * @param user 用户信息
     * @return 响应信息
     */
    @PostMapping("/direct")
    public Map<String, Object> registerUserDirect(@RequestBody User user) {
        logger.info("直接注册用户请求: {}", user);
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            User savedUser = userService.handleUserRegistration(user);
            response.put("success", true);
            response.put("message", "用户直接注册成功");
            response.put("user", savedUser);
            logger.info("用户直接注册成功: id={}, email={}", savedUser.getId(), savedUser.getEmail());
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "直接注册失败: " + e.getMessage());
            logger.error("直接注册用户失败", e);
        }
        
        return response;
    }

    /**
     * 获取用户状态信息
     * @return 简单的状态信息
     */
    @GetMapping("/status")
    public Map<String, Object> getStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("service", "Spring Integration User Registration Service");
        status.put("status", "运行中");
        status.put("integration_channel", "userInputChannel");
        status.put("h2_console", "http://localhost:8080/h2-console");
        return status;
    }

    /**
     * 用户服务健康检查端点
     * @return 健康状态
     */
    @GetMapping("/health")
    public Map<String, String> health() {
        Map<String, String> health = new HashMap<>();
        health.put("status", "UP");
        health.put("service", "UserController");
        return health;
    }
}
